package com.xtedu.examproject.listener;

import com.xtedu.examproject.entity.Course;
import com.xtedu.examproject.entity.Examination;
import com.xtedu.examproject.scheduler.QuartzScheduler;
import com.xtedu.examproject.service.CourseService;
import com.xtedu.examproject.service.ExaminationService;
import com.xtedu.examproject.util.RedisUtil;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import org.quartz.SchedulerException;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebListener
public class SysListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        initCourseToRedis();
        initExamToRedis();
        // 启动任务调度器
        try {
            QuartzScheduler.start();
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        RedisUtil.close();
        try {
            QuartzScheduler.shutdown();
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * 初始化考试数据到redis中
     * */
    public void initExamToRedis() {
        ExaminationService examinationService = new ExaminationService();
        try {
            // 获取所有考试信息
            List<Examination> examinations = examinationService.getAllExamination();
            //分科目存储到Redis中
            Map<Integer, List<Examination>> examCourse = examinations.stream().collect(
                    Collectors.groupingBy(Examination::getCourseId)
            );
            examCourse.forEach((courseId, examList) -> {
                RedisUtil.del("exam:" + courseId);//删除旧的数据
                RedisUtil.setObject("exam:" + courseId, examList);
            });
        } catch (Exception e) {
            //需要记录日志
            e.printStackTrace();
        }

    }

    /*
     * 初始化科目到redis中
     * */
    public void initCourseToRedis() {
        try {
            CourseService courseService = new CourseService();
            List<Integer> courseIds = courseService.findAllCourse().stream().map(Course::getId).toList();
            RedisUtil.setObject("courseIds", courseIds, 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}